package dao

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"order_srv/basic/config"

	__ "order_srv/basic/orderproto"
	"order_srv/handler/models"
	"order_srv/pkg"
	"time"
)

// 订单疑义添加
func DoubtAdd(in *__.DoubtAddReq) (*models.Doubt, error) {
	var doubt models.Doubt
	var orders models.Orders
	err := orders.GetOrderInfo(int(in.OrderId))
	if err != nil {
		return nil, errors.New("查看订单失败")
	}
	if orders.Id == 0 {
		return nil, errors.New("订单不存在")
	}
	if orders.OrderStatus != 5 && orders.OrderStatus != 4 {
		return nil, errors.New("订单未完成，不能添加疑义")
	}

	doubt.OrderId = in.OrderId
	err = doubt.GetDoubtOrderIdInfo()
	if err != nil {
		return nil, err
	}
	if doubt.Id > 0 {
		return nil, errors.New("订单已添加疑义")
	}

	// 检查调帐后金额是否合法
	if in.LaterAmount <= 0 {
		return nil, errors.New("调帐后金额不能小于等于0")
	}

	doubt.DoubtOn = uuid.NewString()
	doubt.OrderId = in.OrderId
	doubt.UserId = in.UserId
	doubt.PreviousAmount = orders.Price         //调帐前订单金额
	doubt.LaterAmount = float64(in.LaterAmount) //调帐后订单金额

	doubt.StartTime = time.Now()                  //调帐开始时间
	doubt.EndTime = time.Now().Add(time.Hour * 3) //调帐结束时间

	if orders.Price > float64(in.LaterAmount) {
		doubt.AdjustmentType = 1 //调帐类型充值
	} else {
		doubt.AdjustmentType = 2 //调帐类型扣款
	}

	// 检查调帐原因是否包含敏感词
	if !pkg.Baid(in.Reason) {
		return nil, errors.New("调帐原因包含敏感词")
	}
	doubt.Reason = in.Reason //调帐原因

	err = doubt.DoubtAdd()
	if err != nil {
		return nil, err
	}
	return &doubt, nil
}

// 订单疑义删除
func DoubtDel(in *__.DoubtDelReq) (*models.Doubt, error) {
	var doubt models.Doubt

	doubt.UserId = in.UserId
	err := doubt.DoubtDetail(int(in.Id))
	if err != nil {
		return nil, errors.New("订单疑义查找失败")
	}
	if doubt.Id == 0 {
		return nil, errors.New("订单疑义不存在")
	}
	doubt.Id = in.Id
	err = doubt.DoubtDel()
	if err != nil {
		return nil, errors.New("删除失败")
	}
	return &doubt, nil
}

// 订单疑义修改
func DoubtUpdate(in *__.DoubtUpdateReq) (*models.Doubt, error) {
	var doubt models.Doubt
	doubt.UserId = in.UserId
	err := doubt.DoubtDetail(int(in.Id))
	if err != nil {
		return nil, errors.New("订单疑义查找失败")
	}
	if doubt.Id == 0 {
		return nil, errors.New("订单疑义不存在")
	}
	if doubt.Status != 1 {
		return nil, errors.New("订单疑义已处理，不能修改")
	}

	var orders models.Orders
	err = orders.GetOrderInfo(int(doubt.OrderId))
	if err != nil {
		return nil, errors.New("查看订单失败")
	}
	if orders.Id == 0 {
		return nil, errors.New("订单不存在")
	}

	if float64(in.LaterAmount) == doubt.LaterAmount {
		return nil, errors.New("调帐后金额不能与调帐前金额相同")
	}
	if orders.Price == float64(in.LaterAmount) {
		return nil, errors.New("调帐后金额不能与订单金额相同")
	}

	// 检查调帐后金额是否合法
	if in.LaterAmount <= 0 {
		return nil, errors.New("调帐后金额不能小于等于0")
	}
	doubt.LaterAmount = float64(in.LaterAmount) //调帐后的价格

	if orders.Price > float64(in.LaterAmount) {
		doubt.AdjustmentType = 1 //调帐类型充值
	} else {
		doubt.AdjustmentType = 2 //调帐类型扣款
	}

	if doubt.EndTime.Before(time.Now()) {
		return nil, errors.New("调帐时间已过，不能修改")
	}

	err = doubt.DoubtUpdate()
	if err != nil {
		return nil, errors.New("修改失败")
	}

	return &doubt, nil
}

// 订单疑义展示
func DoubtList(in *__.DoubtListReq) ([]*__.DoubtList, error) {
	var doubt models.Doubt
	var doubtList []*__.DoubtList
	doubt.UserId = in.UserId
	doubt.Status = uint8(in.Status)
	list, err := doubt.DoubtList(int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, errors.New("获取订单疑义列表失败")
	}

	for _, m := range list {
		StartTime := m.StartTime.Format("2006-01-02 15:04:05")
		EndTime := m.EndTime.Format("2006-01-02 15:04:05")
		doubtList = append(doubtList, &__.DoubtList{
			Id:             m.Id,
			OrderId:        m.OrderId,
			UserId:         m.UserId,
			PreviousAmount: float32(m.PreviousAmount),
			LaterAmount:    float32(m.LaterAmount),
			StartTime:      StartTime,
			EndTime:        EndTime,
			AdjustmentType: uint64(m.AdjustmentType),
			Reason:         m.Reason,
		})
	}
	return doubtList, nil
}

// 订单疑义详情
func DoubtDetail(in *__.DoubtDetailReq) (*models.Doubt, error) {
	var doubt models.Doubt
	doubt.UserId = in.UserId
	err := doubt.DoubtDetail(int(in.Id))
	if err != nil {
		return nil, errors.New("获取订单疑义详情失败")
	}
	if doubt.Id == 0 {
		return nil, errors.New("订单疑义不存在")
	}
	return &doubt, nil
}

// 订单疑义修改状态
func DoubtUpdateStatus(in *__.DoubtUpdateStatusReq) (*models.Doubt, error) {
	var doubt models.Doubt
	doubt.UserId = in.UserId
	err := doubt.DoubtDetail(int(in.Id))
	if err != nil {
		return nil, errors.New("获取订单疑义详情失败")
	}
	if doubt.Id == 0 {
		return nil, errors.New("订单疑义不存在")
	}
	if doubt.Status != 1 {
		return nil, errors.New("订单疑义已处理，不能修改")
	}
	doubt.Id = in.Id
	doubt.Status = uint8(in.Status)
	err = doubt.DoubtUpdateStatus()
	if err != nil {
		return nil, errors.New("订单疑义处理失败")
	}

	var orders models.Orders
	err = orders.GetOrderInfo(int(doubt.OrderId))
	if err != nil {
		return nil, errors.New("查看订单失败")
	}
	if orders.Id == 0 {
		return nil, errors.New("订单不存在")
	}

	if in.Status == 2 {
		now := time.Now()
		month := now.Month()
		day := now.Day()
		content := fmt.Sprintf("%d月%d日从%v到%v的订单金额已由%v元调整为%v元", month, day, orders.StartLoc, orders.EndLoc, doubt.PreviousAmount, doubt.LaterAmount)
		key := "doubt_" + fmt.Sprintf("%d", doubt.Id)
		marshal, err := json.Marshal(content)
		if err != nil {
			return nil, err
		}
		config.Rdb.Set(context.Background(), key, marshal, time.Hour*24)
		orders.Id = uint32(doubt.OrderId)
		orders.Price = doubt.LaterAmount
		err = orders.UpdateOrderStatus()
		if err != nil {
			return nil, err
		}
	}
	return &doubt, nil
}

// 优惠券创建
func CouponTemplateAdd(in *__.CouponTemplateAddReq) (*models.CouponTemplate, error) {
	var couponTemplate models.CouponTemplate
	couponTemplate.Title = in.Title                      //优惠券名称
	couponTemplate.Description = in.Description          //优惠券使用规则
	couponTemplate.CouponType = uint8(in.CouponType)     //优惠券类型
	couponTemplate.Price = float64(in.Price)             //优惠券面额
	couponTemplate.Discount = uint8(in.Discount)         //折扣 1-8折 2-8.5折 3-9折 4-9.5折
	couponTemplate.Limit = uint8(in.Limit)               //限定车辆类型 0-无 1-经济型 2-豪华型
	couponTemplate.SpecificCity = uint8(in.SpecificCity) //指定城市 0-无 1-北京 2-上海 3-广州 4-深圳
	err := couponTemplate.CouponTemplateAdd()
	if err != nil {
		return nil, errors.New("优惠券创建失败")
	}
	return &couponTemplate, nil
}
